import { ref, onMounted, onUnmounted, watch, getCurrentInstance } from "vue";
import { useStomp } from "./useStomp";
import { registerWebSocketInstance } from "@/plugins/websocket";
import { Auth } from "@/utils/auth";
import { ElMessage } from "element-plus";

let globalInstance: ReturnType<typeof createOnlineCountHook> | null = null;
let componentRefCount = 0;

function createOnlineCountHook() {
  const onlineUserCount = ref(0);
  const lastUpdateTime = ref(0);
  const isConnected = ref(false);
  const isConnecting = ref(false);
  let subscribeRetryTimer: NodeJS.Timeout | null = null;

  const stompInstance = useStomp({
    reconnectDelay: 15000,
    maxReconnectAttempts: 3,
    connectionTimeout: 10000,
    useExponentialBackoff: true,
    url: import.meta.env.VITE_APP_WS_ENDPOINT,
  });

  const {
    connect,
    subscribe,
    unsubscribe,
    disconnect,
    isConnected: stompConnected,
  } = stompInstance;

  registerWebSocketInstance("onlineCount", stompInstance);

  let subscriptionId = "";
  let connectionTimeoutTimer: NodeJS.Timeout | null = null;

  const subscribeToOnlineCount = () => {
    if (subscribeRetryTimer) {
      clearTimeout(subscribeRetryTimer);
      subscribeRetryTimer = null;
    }

    if (!stompConnected.value) {
      subscribeRetryTimer = setTimeout(subscribeToOnlineCount, 10000);
      return;
    }

    if (subscriptionId) {
      unsubscribe(subscriptionId);
    }

    subscriptionId = subscribe("/topic/online-count", (message) => {
      try {
        const data = message.body;
        const count =
          typeof data === "number" ? data : JSON.parse(data).count || parseInt(data, 10);

        if (!isNaN(count)) {
          onlineUserCount.value = count;
          lastUpdateTime.value = Date.now();
        }
      } catch (error) {
        console.error("[useOnlineCount] 解析在线用户数量失败:", error);
      }
    });
  };

  const initWebSocket = () => {
    if (isConnecting.value || isConnected.value) return;

    const wsEndpoint = import.meta.env.VITE_APP_WS_ENDPOINT;
    if (!wsEndpoint) {
      console.log("[useOnlineCount] 未配置WebSocket端点(VITE_APP_WS_ENDPOINT),跳过WebSocket连接");
      return;
    }

    const accessToken = Auth.getAccessToken();
    if (!accessToken) {
      console.log("[useOnlineCount] 没有检测到有效令牌，不尝试WebSocket连接");
      return;
    }

    isConnecting.value = true;
    console.log("[useOnlineCount] 开始建立WebSocket连接...");

    clearTimeout(connectionTimeoutTimer as NodeJS.Timeout);
    connectionTimeoutTimer = setTimeout(() => {
      if (!isConnected.value) {
        console.warn("[useOnlineCount] WebSocket连接超时，将自动尝试重连");
        ElMessage.warning("正在尝试连接服务器，请稍候...");
      }
    }, 10000);

    connect();
  };

  const closeWebSocket = () => {
    if (subscriptionId) {
      unsubscribe(subscriptionId);
      subscriptionId = "";
    }
    if (connectionTimeoutTimer) {
      clearTimeout(connectionTimeoutTimer);
      connectionTimeoutTimer = null;
    }
    if (subscribeRetryTimer) {
      clearTimeout(subscribeRetryTimer);
      subscribeRetryTimer = null;
    }

    disconnect();
    isConnected.value = false;
    isConnecting.value = false;
  };

  watch(stompConnected, (connected) => {
    if (connected) {
      isConnected.value = true;
      isConnecting.value = false;
      clearTimeout(connectionTimeoutTimer as NodeJS.Timeout);
      subscribeToOnlineCount();
      console.log("[useOnlineCount] WebSocket连接成功，已订阅在线用户计数主题");
    } else if (!isConnecting.value) {
      isConnected.value = false;
    }
  });

  window.addEventListener("beforeunload", () => {
    closeWebSocket();
  });

  return {
    onlineUserCount,
    lastUpdateTime,
    isConnected,
    isConnecting,
    initWebSocket,
    closeWebSocket,
  };
}

export function useOnlineCount(options: { autoInit?: boolean } = {}) {
  const { autoInit = true } = options;

  if (!globalInstance) {
    globalInstance = createOnlineCountHook();
  }

  const instance = getCurrentInstance();
  if (instance) {
    componentRefCount++;

    onUnmounted(() => {
      componentRefCount--;
      console.log(`[useOnlineCount] 组件卸载，剩余引用: ${componentRefCount}`);

      if (componentRefCount <= 0 && globalInstance) {
        console.log("[useOnlineCount] 无组件引用，关闭WebSocket连接");
        globalInstance.closeWebSocket();
      }
    });
  }

  if (autoInit && instance) {
    onMounted(() => {
      if (!globalInstance!.isConnected.value && !globalInstance!.isConnecting.value) {
        console.log("[useOnlineCount] 组件挂载，尝试初始化WebSocket连接");
        globalInstance!.initWebSocket();
      } else {
        console.log("[useOnlineCount] WebSocket已连接或正在连接，跳过初始化");
      }
    });
  }

  return globalInstance;
}
